package y23.Oct;

class HashBucket {
    private static class Node {
        private int key;
        private int value;
        Node next;


        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }


    private Node[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小

    public void put(int key, int value) {
        int index = key% DEFAULT_SIZE;
        Node list = array[index];
        for (Node cur = list; cur != null; cur = cur.next) {
            if (cur.key == key) {
                cur.value = value;
                return;
            }
        }
        Node newNode = new Node(key, value);
        newNode.next = list;
        array[index] = newNode;
        size++;
        if (loadFactor() > LOAD_FACTOR) {
            resize();
        }
    }


    private void resize() {
        Node[] newArray = new Node[DEFAULT_SIZE * 2];
        for (int i = 0; i < DEFAULT_SIZE; i++) {
            for (Node cur = array[i]; cur != null; cur = cur.next) {
                int index = cur.key % newArray.length;
                Node newNode = new Node(cur.key, cur.value);
                newNode.next = newArray[index];
                newArray[index] = newNode;
            }
        }
        array = newArray;
    }


    private double loadFactor() {
        return size * 1.0 / DEFAULT_SIZE;
    }


    public HashBucket() {
        array = new Node[DEFAULT_SIZE];
    }


    public int get(int key) {
        int index = key% DEFAULT_SIZE;
        Node list = array[index];
        for (Node cur = list; cur != null; cur = cur.next) {
            if (cur.key == key) {
                return cur.value;
            }
        }
        return -1;
    }
}
public class Test8 {
    public static void main(String[] args) {
        HashBucket hashBucket = new HashBucket();
        hashBucket.put(2,12);
        hashBucket.put(3,13);
        hashBucket.put(4,14);
        hashBucket.put(5,15);
        hashBucket.put(6,16);
        hashBucket.put(7,17);
        hashBucket.put(8,18);
        System.out.println("---------------");
        int ret = hashBucket.get(7);
        System.out.println(ret);
    }
}
